package com.jacobson.huobi.mvp

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.jacobson.core.base.Immersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.mvp.BaseMvpActivity
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.common.constants.UserTypeConstant
import com.jacobson.huobi.di.components.DaggerEditSoftwareActivityComponent
import com.jacobson.huobi.di.modules.EditSoftwareActivityModule
import com.jacobson.huobi.entities.events.LoginEvent
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.vo.LoginRespVo
import com.jacobson.huobi.mvp.contract.EditSoftwareContract
import com.jacobson.huobi.mvp.fragment.SettingFragment
import com.jacobson.huobi.mvp.fragment.SymbolFragment
import com.jacobson.huobi.threads.TokenThread
import com.jacobson.huobi.utils.LogcatUtil
import com.jacobson.huobi.utils.ResourcesUtil
import com.jacobson.huobi.utils.TokenStorageUtil
import kotlinx.android.synthetic.main.activity_edit_password.btnBack
import kotlinx.android.synthetic.main.activity_edit_software.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.simple.eventbus.EventBus

@Immersive(fitSystemWindows = false)
class EditSoftwareActivity :
    BaseMvpActivity<EditSoftwareContract.Presenter>(), EditSoftwareContract.View {

    private var settingFragment = SettingFragment.newInstance()

    private var isEditSyetem = false

    private var loginRespVo: LoginRespVo? = null



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //修改底部功能键背景色 只支持api为21及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor =
                ResourcesUtil.getColor(R.color.colorPrimary) //设定底部导航栏  同全局颜色
        }
    }


    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerEditSoftwareActivityComponent.builder()
            .editSoftwareActivityModule(EditSoftwareActivityModule(this))
            .appComponent(appComponent)
            .activityModule(ActivityModule(this))
            .build()
            .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_edit_software

    override fun initData(savedInstanceState: Bundle?) {

        //读取登陆用户信息
        loginRespVo = TokenStorageUtil.read()

        initFrame()
        initBtnClick()
    }

    override fun onLogoutResultResp(response: CommonResponse<JSONObject>) {
        TokenThread.stop()
        TokenStorageUtil.save("")
        EventBus.getDefault().post(LoginEvent(1, null))
        MainActivity.startHomeActivity(this, SymbolFragment.ME)
    }

    override fun onLogcatUploadResultResp(response: CommonResponse<String>) {
        btnUploadLogcat.visibility = View.VISIBLE
        if (response.code == Constants.RESP_OK) {
            Toast.makeText(this, "日志提交成功", Toast.LENGTH_SHORT).show()
        }

    }

    override fun onError(type: Int, extra: Any?, code: Int, message: String): Boolean {
        logger.e("error >>> $message")
        return super.onError(type, extra, code, message)
    }

    private fun initFrame() {
        fragmentManager.beginTransaction()
            .add(R.id.tvPreferenceContainer, settingFragment)
            .commit()
    }

    private fun initBtnClick() {
        btnBack.setOnClickListener {
            tvEditSoftwareTitle.text = "软件设置"
            if (isEditSyetem) {
                isEditSyetem = false
                tvSoftware.visibility = View.VISIBLE
                tvPreferenceContainer.visibility = View.GONE
            } else {
                this.finish()
            }
        }

        //语言设置
//        btnEditSoftwareLanguage.setOnClickListener {
//
//            var itemList = arrayOf("中文", "English")
//            var choice = -1
//            AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher)
//                .setTitle("语言选择")
//                .setSingleChoiceItems(itemList, 0,
//                    DialogInterface.OnClickListener { dialogInterface, i -> choice = i })
//                .setPositiveButton("确定",
//                    DialogInterface.OnClickListener { dialogInterface, i ->
//                        if (choice !== -1) {
//                            Toast.makeText(
//                                this,
//                                "你选择了" + itemList.get(choice),
//                                Toast.LENGTH_LONG
//                            ).show()
//                        }
//                    }).create().show()
//        }

        //系统设置
        btnEditSoftwareSystem.setOnClickListener {
            isEditSyetem = true
            tvEditSoftwareTitle.text = "系统设置"
            fragmentManager.beginTransaction()
                .show(settingFragment)
                .commit()

            tvSoftware.visibility = View.GONE
            tvPreferenceContainer.visibility = View.VISIBLE
        }

        //登出
        btnLoginOut.setOnClickListener {
            btnLoginOut.visibility = View.GONE
            presenter.logout()

        }
        //提交上传日志
        btnUploadLogcat.setOnClickListener {
            var file = LogcatUtil.getLogcatInfo(loginRespVo!!.userId)
            if (file == null) {
                Toast.makeText(this, "保存日志文件失败,无法上传", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            var requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            // MultipartBody.Part  和后端约定好Key，这里的partName是用file
            var body = MultipartBody.Part.createFormData("file", file.name, requestFile)
            presenter.logcatUpload(body, getModel(), getOs())
            btnUploadLogcat.visibility = View.GONE
        }

        if (loginRespVo != null && !loginRespVo!!.accessToken.isNullOrEmpty()) {
            btnLoginOut.visibility = View.VISIBLE
        }
        if (loginRespVo != null && UserTypeConstant.isAdmin(loginRespVo!!.vipLevel)) {
            btnUploadLogcat.visibility = View.VISIBLE
        } else {
            btnUploadLogcat.visibility = View.GONE
        }
    }

    /**
     * 获取操作系统
     */
    private fun getOs(): String {
        return Build.VERSION.RELEASE
    }

    /**
     * 获取型号
     */
    private fun getModel(): String {
        return Build.MODEL
    }

    companion object {
        fun startActivity(context: Context) {
            Intent(context, EditSoftwareActivity::class.java).run {
                context.startActivity(this)
            }
        }

    }

}
